* Load your dataset
use 20%.dta, clear
rename trend date
* The dataset should contain:
* - date: time periods (e.g., months or years)
* - firm_id: unique firm identifier
* - return: dependent variable (e.g., stock returns)
* - independent variables: predictors (e.g., firm characteristics)

* Sort data by time and firm
sort date firm

* Step 1: Run cross-sectional regressions for each time period
* Save regression coefficients for each period
gen beta1 = .
gen beta2 = .
gen beta3 = .
gen beta4 = .
gen beta5 = .
gen intercept = .
gen resid = .
gen n_obs = .

levelsof date, local(dates)

foreach t of local dates {
    reg cds_return sentiment leverage mktrf smb hml, robust if date == `t'
	*reg return independent_variable1 independent_variable2 if date == `t'
    
    * Store coefficients
    replace beta1 = _b[sentiment] if date == `t'
    replace beta2 = _b[leverage] if date == `t'
	replace beta2 = _b[mktrf] if date == `t'
	replace beta2 = _b[smb] if date == `t'
	replace beta2 = _b[hml] if date == `t'
    replace intercept = _b[_cons] if date == `t'

    * Store residuals
    predict resid if date == `t', resid
    
    * Record sample size
    count if date == `t'
    replace n_obs = r(N) if date == `t'
}

* Step 2: Compute average coefficients (Fama-MacBeth estimates)
summarize beta1
local avg_beta1 = r(mean)
local se_beta1 = r(se)

summarize beta2
local avg_beta2 = r(mean)
local se_beta2 = r(se)

summarize beta3
local avg_beta3 = r(mean)
local se_beta3 = r(se)

summarize beta4
local avg_beta4 = r(mean)
local se_beta4 = r(se)

summarize beta5
local avg_beta5 = r(mean)
local se_beta5 = r(se)

summarize intercept
local avg_intercept = r(mean)
local se_intercept = r(se)

* Display Fama-MacBeth regression results
di "Fama-MacBeth Estimates:"
di "Sentiment: Coefficient = `avg_beta1', SE = `se_beta1'"
di "Leverage: Coefficient = `avg_beta2', SE = `se_beta2'"
di "Market: Coefficient = `avg_beta3', SE = `se_beta3'"
di "Smb: Coefficient = `avg_beta4', SE = `se_beta4'"
di "Hml: Coefficient = `avg_beta5', SE = `se_beta5'"
di "Intercept: Coefficient = `avg_intercept', SE = `se_intercept'"

* Optional: Save Fama-MacBeth results to a new dataset
*gen avg_coef1 = `avg_beta1'
*gen avg_coef2 = `avg_beta2'
*gen avg_intercept = `avg_intercept'
*save fama_macbeth_results.dta, replace
